package model

import (
	"github.com/google/uuid"
	"gorm.io/gorm"
	"travel-app/common/initialize"
	"travel-app/common/proto/travel"
)

type name struct {
}

type Area struct {
	gorm.Model
	Name    string  `gorm:"type:varchar(20);not null;index:ip_idx"`
	Address string  `gorm:"type:varchar(50);not null;index:ip_idx"`
	Ticket  float64 `gorm:"type:decimal(10,2);not null;index:ip_idx"`
	Status  int64   `gorm:"type:int(10);not null;index:ip_idx"`
	Stock   int64   `gorm:"type:int(10);not null;index:ip_idx"`
	Comment string  `gorm:"type:varchar(50);not null;index:ip_idx"`
	Like    int     `gorm:"type:int(10);not null;index:ip_idx"`
}

func (a Area) FindArea(name string) (area []*Area, err error) {
	err = initialize.DB.Where("name=?", name).Take(&area).Error
	if err != nil {
		return nil, err
	}
	return
}
func (a Area) FindAreas(name int64) (area *Area, err error) {
	err = initialize.DB.Where("id=?", name).Take(&area).Error
	if err != nil {
		return nil, err
	}
	return
}

type Insurance struct {
	gorm.Model
	Name   string  `gorm:"type:varchar(20);not null;index:ip_idx"`
	Price  float64 `gorm:"type:decimal(10,2);not null;index:ip_idx"`
	Status int     `gorm:"type:int(10);not null;index:ip_idx"`
}

type Order struct {
	gorm.Model
	AreaId       int64   `gorm:"type:int(10);not null;index:ip_idx"`
	UserId       int64   `gorm:"type:int(10);not null;index:ip_idx"`
	OrderSn      string  `gorm:"type:varchar(50);not null;index:ip_idx"`
	Sum          int64   `gorm:"type:int(10);not null;index:ip_idx"`
	Price        float64 `gorm:"type:decimal(10,2);not null;index:ip_idx"`
	Days         string  `gorm:"type:datetime;index:ip_idx"`
	TicketStatus int64   `gorm:"type:int(10);not null;index:ip_idx"`
	Status       int64   `gorm:"type:int(10);not null;index:ip_idx"`
	Insurance    int64   `gorm:"type:int(10);not null;index:ip_idx"`
}

func (o Order) CreateTicket(in *travel.BuyTicKetReq) (order *Order, err error) {

	a := &Area{}
	initialize.DB.Where("id=?", in.AreaId).Find(&a)

	OrderSn := uuid.New().String()

	order = &Order{
		AreaId:       in.AreaId,
		UserId:       in.UserId,
		OrderSn:      OrderSn,
		Sum:          in.Sum,
		Price:        a.Ticket * float64(in.Sum),
		Days:         in.Days,
		TicketStatus: in.TicketStatus,
		Status:       0,
		Insurance:    in.Insurance,
	}

	err = initialize.DB.Create(&order).Error
	if err != nil {
		return nil, err
	}
	return

}

func (o Order) Update(in *travel.PayCallbackReq) (order *Order, err error) {
	err = initialize.DB.Model(&Order{}).Where("order_sn=?", in.OrderSn).Update("status", 1).Error
	if err != nil {
		return nil, err

	}
	return
}

func (o Order) FindOrder(id int64) (order []*Order, err error) {
	err = initialize.DB.Where("user_id=?", id).Find(&order).Error
	if err != nil {
		return nil, err
	}
	return
}

func (o Order) DelOrder(sn string) bool {
	err := initialize.DB.Where("order_sn=?", sn).Delete("order_sn").Error
	if err != nil {
		return false
	}
	return true
}
